import java.awt.Rectangle;
import java.util.ArrayList;


public class TargetControler extends Thread {

	private static ArrayList<Target> arrayTarget = new ArrayList<Target>();
	private static int numberOfTarget;
	private Map map;
	private boolean state = true;
	public boolean paused = false;
	public Target lastTargetKilled;

	private int last_combo;

	public TargetControler(Map map){
		this.map = map;
		arrayTarget = map.getTargetArray();
		numberOfTarget = arrayTarget.size();
	}

	public static ArrayList<Target> getArray(){
		return arrayTarget;
	}

	/**
	 * Permet de gerer les collision entre les targets et l'oeufs du joueur.
	 * @param _egg oeuf du joueur.
	 * @return vrai(true) si il y a collision.
	 */
	public int updatePhysics(Egg _egg) {
		int typeOfCollision = 0;
		Rectangle eggRec = new Rectangle(	(int)_egg.x,
				(int)_egg.y, 
				_egg.getImageWidth(), 
				_egg.getImageHeight());
		this.last_combo = 0;
		for (Target element : arrayTarget) {	
			Rectangle targetRec = new Rectangle((int)element.getX(),
					(int)element.getY(),
					element.getImageWidth(), 
					element.getImageHeight());

			if(element.isAlive() && eggRec.intersects(targetRec) && !_egg.isExploding()) {
				element.receiveDamage(_egg.getType());
				if(!element.isAlive()) {
					element.explose();
					numberOfTarget--;
					this.lastTargetKilled = element;
				}
				typeOfCollision = 5;
				this.last_combo += 1;
			}
		}

		return typeOfCollision;
	}

	public int getLastComboShot(){
		int last_C = this.last_combo;

		this.last_combo = 0;
		return last_C;
	}

	/**
	 * Calcul le nombre de target restantes
	 * @return nombre de target encore en vie.
	 */
	public int getNumberOfTargetLeft(){
		return numberOfTarget;
	}

	@Override
	public void run() {

		while(state) {
			if(!paused) {
				for(Target element : arrayTarget){
					element.update(map);
				}
			}
			try {Thread.sleep(25);} catch (InterruptedException e) {}	
		}
	}

	public void kill() {
		state = false;
	}
}
